namespace Test
{
    internal static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.ApplicationExit += new EventHandler(OnApplicationExit);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // To customize application configuration such as set high DPI settings or default font,
            // see https://aka.ms/applicationconfiguration.
            ApplicationConfiguration.Initialize();
            DmServer.Core.Base.ApplicationContext.LazyInitializer();
            Application.Run(new MainForm());
        }
        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }
        static void OnApplicationExit(object sender, EventArgs e)
        {
            // 执行应用程序退出时的清理工作
            CloseSearchServerIfLastInstance();
        }
        static void HandleException(Exception ex)
        {
            // 记录日志
            LogException(ex);
            // 执行应用程序退出时的清理工作
            CloseSearchServerIfLastInstance();

            // 通知用户
            MessageBox.Show("程序遇到严重错误并将关闭。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            // 强制退出应用程序
            Application.Exit();
        }

        static void LogException(Exception ex)
        {
            if (ex != null)
            {
                // 将异常信息写入日志文件
                System.IO.File.AppendAllText("error.log", $"{DateTime.Now}: {ex.ToString()}\n");
            }
        }
        public static void CloseSearchServerIfLastInstance()
        {
            if (MainForm.client != null)
            {
                MainForm.client.CloseAsync();
                MainForm.client.SafeDispose();
            }

            string currentProcessName = Process.GetCurrentProcess().ProcessName;
            Process[] runningInstances = Process.GetProcessesByName(currentProcessName);

            if (runningInstances.Length == 1) // If this is the last instance
            {
                // 尝试终止指定的进程
                KillSpecificProcess("SearchServer");
            }
        }
        public static void KillSpecificProcess(string processName)
        {
            Process[] processes = Process.GetProcessesByName(processName);

            foreach (Process process in processes)
            {
                try
                {
                    process.Kill();
                    process.WaitForExit(); // 等待进程退出
                }
                catch (Exception ex)
                {
                    // 记录无法终止进程的异常
                    System.IO.File.AppendAllText("error.log", $"{DateTime.Now}: 无法终止进程 {processName}: {ex.Message}\n");
                }
            }
        }
    }
}